package com.cskaoyan.service;

import com.cskaoyan.bean.Admin;
import com.cskaoyan.bean.AdminExample;
import com.cskaoyan.bean.InfoBean;
import com.cskaoyan.mapper.AdminMapper;
import com.cskaoyan.mapper.RoleMapper;
import com.cskaoyan.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
public class AdminLoginServiceImpl implements AdminLoginService {

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    RoleMapper roleMapper;

    @Transactional
    @Override
    public void update(Admin admin) {
        AdminExample adminExample = new AdminExample();
        adminExample.createCriteria().andUsernameEqualTo(admin.getUsername()).andDeletedEqualTo(false);
        adminMapper.updateByExampleSelective(admin, adminExample);
    }

    @Override
    public InfoBean getLoginInfo(Admin admin1) {
        List<Admin> admins = adminMapper.selectAdminByName(admin1.getUsername());
        Admin admin = admins.size() >= 1?admins.get(0):null;
        if(admin == null){
            return null;
        }
        String roleIds = admin.getRoleIds();
        String[] split = StringUtils.toStringArray(roleIds);
        List<String> roles = roleMapper.selectRoleNameByRoleId(split);
        String username = admin.getUsername();
//        List<String> perms = adminMapper.selectPermissionByUsername(username);
        List<String> perms = adminMapper.selectPermissionByRoleId(split);
        InfoBean info = new InfoBean();
        info.setPerms(perms);
        info.setAvatar(admin.getAvatar());
        info.setName(username);
        info.setRoles(roles);
        return info;
    }
}
